<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\ApprovalLogModel;
use app\admin\model\ArchivesDeceasedModel;
use app\admin\model\ContractModel;
use app\admin\model\OrderModel;
use app\admin\model\ProductInfoModel;
use app\admin\model\RetreatTombModel;
use app\admin\model\ServiceMoveModel;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\AdminMenuModel;

class MoveController extends AdminBaseController
{

    protected $customerId =0;
    protected $tombId =0;
    protected $tomb_type =0;
    protected $tomb_typei =0;
    protected $tomb_num =0;
    protected $result_list =0;

    public function initialize()
    {
        parent::initialize();
//        session('customer_id', 0);
        $this->customerId = session('aftersale.customer_id');
        $this->tombId = session('aftersale.tomb_id');
        $this->tomb_type = session('aftersale.tomb_type');

        if ($this->customerId){
            $OrderModel = new OrderModel();
            $result = $OrderModel->getOrderByCustomerId($this->customerId);
            $this->tomb_typei =$result['tomb_typei'];
            $this->result_list =$result;

            $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.id dep_id,c.department_name')
                ->join('dj_department c','c.id=u.dept_id')->where(['u.user_type'=>2,'c.dept_type'=>4])->select();
            $dep = Db::name("department")->where(['dept_type'=>4])->select();
            $costset = Db::name('costset')->where(['id'=>1])->find()  ;

            foreach ($dep as $dk=>&$valued){
                $this->dep_list[$valued['id']]=$valued['department_name'];
            }
            foreach ($users as $dk=>&$valued){
                $this->users_array[$valued['id']]=$valued['user_nickname'];
            }
            $this->tomb_num = $result['tomb_num'];
            $this->assign([
                'result'=>$result,
                'dep_list'=>$dep,
                'user_list'=>$users,
                'costset'=>$costset
            ]);
        }

    }
    public function login(){
        if($this->request->isPost()){
            $param= $this->request->param();
            $customer['token_customer']['customer_id'] = $param['id'];
            $customer['token_customer']['tomb_id'] = $param['tomb_id'];
            //登入成功页面跳转
            session('customer_id', $param['id']);
            session('tomb_id', $param['tomb_id']);
            session('tomb_type', $param['tomb_type']);
            $this->result($customer);
        }
        $param= $this->request->param();
        if (isset($param['ajax']) && $param['ajax']==1){
            $buyer_cart = $param['buyer_cart'];
            $res =  Db::name('customer_info')->alias('ci')
                ->join('dj_order o','o.customer_id = ci.id')
                ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id")
                ->where(['ci.customer_account'=>$buyer_cart])->field('ci.id,ci.buyer_name,ci.buyer_phone,o.order_id,o.tomb_id,o.tomb_num,o.tomb_type,p.tomb_region,p.tomb_address,p.tomb_bit_number')->select();
            $this->result($res);
        }
        return $this->fetch();
    }

    //迁墓业务
	public function index(){

        if ($this->customerId==0){
            return $this->fetch('aftersale/login');
        }
        if ($this->tomb_type ==4 && $this->tomb_typei ==1){
            return $this->redirect(url("aftersale/shouindex"));
        }
        $deceased_list = Db::name('archives_deceased')->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])->select();

        if (empty($deceased_list)){
            return $this->fetch('aftersale/burial');
        }else{
            $this->assign('deceased_list',$deceased_list);
        }
        // 从服务管理的表中取数据
        $service = Db::name('service_move')
            ->where(['tomb_id'=>$this->result_list['tomb_id'],'customer_id'=>$this->customerId])
            ->where("service_status", "neq","3")
            ->order("id","desc")
            ->find();
        $file = '';
        if($service['contract_file']){
            $contract_file = json_decode($service['contract_file']);
            $file ='https://view.officeapps.live.com/op/view.aspx?src=http://gd.zhmyxt.com/'.$contract_file->doc;
        }


        $this->assign('contract_file',$file);
        if(!empty($service)){
            $service['move_time'] = date('Y-m-d H:i');
            $this->assign("service",$service);

            // 查询是审核的信息
            $apinfo = Db::name('approval')->where(['form_id'=>$service['id'],'form_type'=>'2','detail_type'=>'3'])->order("id","desc")->find();
            $this->assign("approvialinfo",$apinfo);
        }


        // 查询迁墓费用
        $costset = Db::name('costset')->field("move_cost")->where(['id'=>1])->find()  ;
        $this->assign("move_cost",$costset);

        // 查询接待人
        $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.department_name')
            ->join('dj_department c','c.id=u.dept_id')
            ->where(['u.user_type'=>2,'c.dept_type'=>4])
            ->select();
        $this->assign("userlist",$users);


		return $this->fetch('aftersale/move');
	}

	/*迁墓业务提交*/
	public function move_post(){
        if ($this->request->post()){
            $param = $this->request->param();


            $ContractModel = new ServiceMoveModel();
            $order_id = $param['order_id'];
            $customer_id = $param['customer_id'];
            $tomb_id = $param['tomb_id'];
            $tomb_num = $param['tomb_num'];

            $submit_status = $param['submit_status'];
            $service_id = $param['service_id'];//服务管理的迁墓的id
            if(!isset($param['is_sms'])){

            }
            if(!isset($param['ids'][0])){
                $this->error("请选择要迁墓的逝者信息！");
            }else{
                $buried_ids = $param['ids'];
            }
            // 发短信
            if(isset($param['is_send'])){
               $iSenf =  sendNoticeSms(2,$param['buyer_phone'],['move_time'=>$param['move_time']],$errorMsg);
                if ($iSenf==false){
                    return $this->error($errorMsg);
                }
            }
            // 从服务管理的表中取数据
            $service = Db::name('service_move')->alias("s")
                ->where(['tomb_id'=>$this->result_list['tomb_id']])
                ->where(['customer_id'=>$customer_id])
                ->where("s.service_status", "eq","1")
                ->where("s.pay_status", "eq","0")
                ->find();

            if(!empty($service)) {
                // 先判断该逝者信息是否已提交审核
                $apinfo = Db::name('approval')->where(['form_id' => $service['id'], 'form_type' => '2', 'detail_type' => '3', 'approval_status' => '1'])->find();
                if (!empty($apinfo)) {
                    $this->error("该迁墓信息正在审核中，不允许修改内容！");
                }
            }
//            if(!empty($service_id)){
//                // 先判断该逝者信息是否已提交审核
//                $apinfo = Db::name('approval')->where(['form_id'=>$service_id,'form_type'=>'2','detail_type'=>'3','approval_status'=>'1'])->find();
//                if(!empty($apinfo)){
//                    $this->error("该迁墓信息正在审核中，不允许修改内容！");
//                }

//                // 更新服务管理的迁墓表
//                $smoves = Db::name('service_move')->where("id",$service_id)->find();
//                $smoves['move_time']  = strtotime($param['move_time']);
//                $smoves['tomb_address']  =  $param['tomb_address'];
//                $smoves['buyer_name']  =  $param['buyer_name'];
//                $smoves['buyer_sex']  =  $param['buyer_sex'];
//                $smoves['buyer_address']  =  $param['buyer_address'];
//                $smoves['buyer_phone']  =  $param['buyer_phone'];
//                $smoves['tombstone_plan']  =   $param['tombstone_plan'];
//                $smoves['handle_id']  =   cmf_get_current_admin_id();
//                $smoves['handle_name']  =   $param['handle_name'];
//                $smoves['service_status']  =  '1';
//                $smoves['add_time']  =  time();
//                $smoves['add_user']  =   cmf_get_current_admin_id();
//                $smoves['url_idcard']  =   $param['url_idcard'];
//                $smoves['url_contract']  =   $param['url_contract'];
//                $smoves['url_burial']  =   $param['url_burial'];
//                $smoves['url_buy']  =   $param['url_buy'];
//                $smoves['url_move']  =   $param['url_move'];
//                $smoves['move_reason']  =   $param['move_reason'];
//                $smoves['move_money']  =   $param['move_money'];
//                $smoves['receptionist']  =   $param['receptionist'];
//                $smoves['submit_status']  =   $param['submit_status'];
//                $smoves['customer_id'] = $param['customer_id'];
//                $smoves['order_id'] = $this->result_list['order_id'];
//                Db::name('service_move')->update($smoves);
//
//                // 更新逝者信息表
//                foreach ($buried_ids as $key=>&$id){
//                    $death = Db::name('archives_deceased')->where(['deceased_id'=>$id])->find();
//                    $death['servicemove_id'] = $service_id;
//                    $death['move_status']  = '1';
//                    Db::name('archives_deceased')->where(['deceased_id'=>$id])->update($death);
//                }
//
//                if($submit_status == '2'){
//
//                    // 如果是提交审核的状态保存审核表
//                    $appdata = array();
//                    $appdata['approval_status'] = '1';
//                    $appdata['approval_desc'] = '';
//                    $appdata['form_type'] = '2';
//                    $appdata['detail_type'] = '3';
//                    $appdata['apply_time'] = time();
//                    $appdata['apply_user'] = cmf_get_current_admin_id();
//                    $appdata['form_id'] = $service_id;
//
//                    Db::name("approval")->insert($appdata);
//                }else if($submit_status == '4'){
//                    // 如果被审核驳回的时候
//                    $appdata = Db::name('approval')->where(['form_id'=>$service_id,'form_type'=>'2','detail_type'=>'3','approval_status'=>'1'])->find();
//
//                    $appdata['approval_status'] = '1';
//                    $appdata['approval_desc'] = '';
//                    $appdata['approval_user'] = '';
//                    $appdata['approval_time'] = '';
//                    $appdata['apply_time'] = time();
//                    $appdata['apply_user'] = cmf_get_current_admin_id();
//
//                    Db::name("approval")->update($appdata);
//                }
//            }else{
                // 插入服务管理的墓位信息表
                $services = array();
                $services['move_time']  = strtotime($param['move_time']);
                $services['tomb_id']  =  $tomb_id;
                $services['tomb_num']  =  $tomb_num;
                $services['tomb_address']  =  $param['tomb_address'];
                $services['buyer_name']  =  $param['buyer_name'];
                $services['buyer_sex']  =  $param['buyer_sex'];
                $services['buyer_address']  =  $param['buyer_address'];
                $services['buyer_phone']  =  $param['buyer_phone'];
                $services['tombstone_plan']  =   $param['tombstone_plan'];
                $services['handle_id']  =   cmf_get_current_admin_id();
                $services['handle_name']  =   $param['handle_name'];
                $services['service_status']  =  '1';
                $services['add_time']  =  time();
                $services['add_user']  =   cmf_get_current_admin_id();
                $services['url_idcard']  =   $param['url_idcard'];
                $services['url_contract']  =   $param['url_contract'];
                $services['url_burial']  =   $param['url_burial'];
                $services['url_buy']  =   $param['url_buy'];
                $services['url_move']  =   $param['url_move'];
                $services['move_reason']  =   $param['move_reason'];
                $services['move_money']  =   $param['move_money'];
                $services['receptionist']  =   $param['receptionist'];
                $services['submit_status']  =   $param['submit_status'];
                $services['customer_id'] = $param['customer_id'];
                $services['order_id'] = $this->result_list['order_id'];

                $serinsert_id = Db::name('service_move')->insertGetId($services);


                // 更新逝者信息表
                $names = "";
                foreach ($buried_ids as $key=>&$id){
                    $death = Db::name('archives_deceased')->where(['deceased_id'=>$id])->find();
                    $names .= $death['deceased_name'] . " ";
                    $death['servicemove_id'] = $serinsert_id;
                    $death['move_status']  = '1';
                    Db::name('archives_deceased')->where(['deceased_id'=>$id])->update($death);
                }

                // 更新迁墓表的逝者姓名
                $death11 = Db::name('service_move')->where(['id'=>$serinsert_id])->find();
                $death11['death_name']  = $names;
                Db::name('service_move')->where(['id'=>$serinsert_id])->update($death11);

                if($submit_status == '2'){
                    // 如果是提交审核的状态保存审核表
                    $appdata = array();
                    $appdata['approval_status'] = '1';
                    $appdata['approval_desc'] = '';
                    $appdata['form_type'] = '2';
                    $appdata['detail_type'] = '3';
                    $appdata['apply_time'] = time();
                    $appdata['apply_user'] = cmf_get_current_admin_id();
                    $appdata['form_id'] = $serinsert_id;

                    Db::name("approval")->insert($appdata);
                }
//            }

            return $this->success('提交成功',url("Move/index",['order_id'=>$order_id,'customer_id'=>$customer_id,'tomb_id'=>$tomb_id]));
        }

		return $this->fetch();
	}

	// 图片下载
    public function photodown(){
	    // 逝者id
        $id = $this->request->param("id");
        $cremation_certificate = Db::name('archives_deceased')->field("cremation_certificate")->where(['deceased_id'=>$id])->find();
        if(!empty($cremation_certificate)){
            //使用绝对路径
            $file_path=$_SERVER['DOCUMENT_ROOT'].$cremation_certificate['cremation_certificate'];

            //打开文件---先判断再操作
            if(!file_exists($file_path)){
                echo "文件不存在";
                return ; //直接退出
            }
            //存在--打开文件
            $fp=fopen($file_path,"r");
            //获取文件大小
            $file_size=filesize($file_path);
            //http 下载需要的响应头
            header("Content-type: application/octet-stream"); //返回的文件
            header("Accept-Ranges: bytes");   //按照字节大小返回
            header("Accept-Length: $file_size"); //返回文件大小
            header("Content-Disposition: attachment; filename=".$cremation_certificate['cremation_certificate']);//这里客户端的弹出对话框，对应的文件名
            //向客户端返回数据
            //设置大小输出
            $buffer=1024;
            //为了下载安全，我们最好做一个文件字节读取计数器
            $file_count=0;

            //判断文件指针是否到了文件结束的位置(读取文件是否结束)
            while(!feof($fp) && ($file_size-$file_count)>0){
                $file_data=fread($fp,$buffer);
                //统计读取多少个字节数
                $file_count+=$buffer;
                //把部分数据返回给浏览器
                echo $file_data;
            }
            //关闭文件
            fclose($fp);
        }
    }
    public function ajax_goods()
    {
        $cate_id = $this->request->param('cate_id');
        $where = ['d.type' => 0, 'd.is_delete' => 0, 'd.if_show' => 1, 'd.cate_p_id' => $cate_id];
        //取库房数据
        $results = Db::name("Goods")->alias("d")->field("d.id,d.goods_name,d.price,d.photos_url,stock")
            ->join("dj_room r", "r.id = d.room", "left")
            ->where($where)->order('d.id', 'DESC')->select();
        $this->result($results);
    }
	/*缴费打证*/
	public function prints(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }

        if ($this->request->isPost()){
            $param = $this->request->param();
            $project_id =[];
            $free_price = 0;
            $deal_price =0;
            $total_price = 0;
            foreach ($param['project'] as $key=>$value){
                $value['order_id'] =$this->result_list['order_id'];
                $value['add_time'] = time();
                $value['pay_id'] = 0;
                $total_price+=$value['total_price'];
                $deal_price+=$value['deal_price'];
                if ($value['free_price']!=0){
                    $free_price+=$value['free_price'];
                }elseif (!empty($value['discount_rate'])){
//                    (unit_price*num)*((100-discount_rate)/100);
                    $free_price+=$value['deal_price'] -$value['total_price'];
                    $value['deal_price'] =(100-$value['deal_price'])/100;
                }
                $project_id[] = Db::name('pay_project')->insertGetId($value);
            }

            $pay_ins = [
                'type'=>3,
                'order_id'=>$this->result_list['order_id'],
                'pay_sn'=>'JS'.date('YmdHi'),
                'tomb_id'=>$this->result_list['tomb_id'],
                'tomb_num'=>$this->result_list['tomb_num'],
                'tom_price'=>0,//购墓价格
                'discount_rate'=>0,//折扣
                'free_price'=>$free_price,//折扣
                'deal_price'=>$deal_price,//成交
//                'deposit_price'=>$param['deposit_price'],//定金
                'total_price'=>$total_price,//应收金额
//                'real_name'=>$param['real_name'],//付款人
//                'real_phone'=>$param['real_phone'],//付款人
//                'pay_type'=>$param['pay_type'],//付款方式
//                'remark'=>$param['remark'],//备注
                'add_time'=>time(),//备注
                'handle'=>cmf_get_current_admin_id(),//收款人
                'pay_real_name'=>cmf_get_current_admin_id(),//收款人
                'status'=> 0,// 付款方式
            ];

            if ($param['pay_id']){
                $rets = Db::name('order_pay_log')->where(['id'=>$param['pay_id']])->update($pay_ins);
                $pay_id = $param['pay_id'];
            }else{
                $rets =   Db::name('order_pay_log')->insertGetId($pay_ins);
                $pay_id = $rets;
            }
            if ($rets != false){
                Db::name('pay_project')->whereIn('project_id',$project_id)->update(['pay_id'=>$pay_id]);
                Db::name('order')->where(['order_id'=>$param['order_id']])->update(['status'=>1]);
                $this->success('提交成功',url('Aftersale/burial'));
            }else{
                $this->success('提交失败，请检查填写内容');
            }
        }
        $data = $this->request->param();
        $order_id =$data['order_id'];// $this->request->param('order_id',0);
        $buried_id = $data['buried_id'];//$this->request->param('buried_id',0);
        $deceased_list = Db::name('archives_deceased')->where(['order_id'=>$order_id])->select();

        $arr_list=[];
        foreach ($deceased_list as $key=>&$value){
            if ($value['type']==1){
                $project_info['project_name'] = '安葬费';
            }else{
                $project_info['project_name'] = '合葬费';
            }
            $project_info['project_unit'] = '位';
            $project_info['project_type'] = '服务';

            $project_info['unit_price']     = $value['funeral_price'];
            $project_info['total_price'] = $value['funeral_price'];
            $project_info['num'] = 1;
            $project_info['type'] = 0;
            $arr_list[] = $project_info;
        }


        $goods_info = Db::name('order_goods')->where(['order_id'=>$order_id,'type'=>2])->find();
        if ($goods_info){
            $goods_info['goods_info'] = json_decode($goods_info['goods_info'],true);
            foreach ($goods_info['goods_info'] as $key=>&$value){
                $g_info['project_name'] = $value['goods_name'];
                $g_info['project_unit'] = '个';
                $g_info['project_type'] = $value['cate_name'];
                $g_info['unit_price']   = $value['goods_price'];
                $g_info['total_price']  = $value['goods_price']*$value['num'];
                $g_info['num']          = $value['num'];
                $g_info['type'] = 1;
                $arr_list[] = $g_info;
            }
        }
        $this->assign([
            'result'=>$this->result_list,
            'arr_list'=>$arr_list
        ]);
		return $this->fetch();
	}
	/*维保业务*/
	public function maintenance(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }

$pro_id = $this->result_list['new_pro'];
        $pro_info =  ProductInfoModel::where(['pro_id'=>$pro_id])->select();

//        exit(json_encode());


        $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.department_name')
            ->join('dj_department c','c.id=u.dept_id')
            ->where(['u.user_type'=>2,'c.dept_type'=>4])
            ->select();
        $this->assign("userlist", $users);
        $this->assign('pro_info',$pro_info);
//        $this->assign('result',[]);
		return $this->fetch();
	}

	/*艺术墓*/
	public function art(){
        if ($this->request->post()){
            $param = $this->request->param();
            $deceased = $param['deceased'];
            $order_id = $param['order_id'];
            $customer_id = $param['customer_id'];
            $tomb_id = $param['tomb_id'];
            $tomb_num = $param['tomb_num'];
            $handle = $param['handle'];
            $buried_id = $handle['buried_id'];


            unset($handle['buried_id']);

            if ($buried_id){
                Db::name('tomb_buried')->where(['buried_id'=>$buried_id])->update($handle);
            }else{
                $handle['is_sms'] = isset($handle['is_sms'])?$handle['is_sms']:0;
                $handle['order_id'] = $order_id;
                $handle['tomb_id'] = $tomb_id;
                $handle['add_time'] = time();
                $buried_id = Db::name('tomb_buried')->insertGetId($handle);
            }

            foreach ($deceased as $key=>&$value){
                $deceased_id = $value['deceased_id'];
                unset($value['deceased_id']);
                $value['order_id'] = $order_id;
                $value['date_funeral'] = $value['funeral_time'];
                $value['add_time'] = time();
                $value['order_id'] = $order_id;
                $value['tomb_id'] = $tomb_id;
                $value['tomb_num'] = $tomb_num;
                $value['customer_id'] = $customer_id;
                $value['buried_id'] = $buried_id;
                if ($deceased_id){
                    $deceased_list = Db::name('archives_deceased')->where(['deceased_id'=>$deceased_id])->update($value);
                }else{
                    if ($value['deceased_name']) {
                        $deceased_list = Db::name('archives_deceased')->insertGetId($value);
                        $deceased_id = $deceased_list;
                    }
                }
                $buried_inst=[
                    'buried_id'=>$buried_id,
                    'order_id'=>$order_id,
                    'tomb_id'=>$tomb_id,
                    'tomb_num'=>$tomb_num,
                    'tomb_address'=>$this->result_list['tomb_region'],
                    'dealer_user'=>$handle['contact_name'],
                    'dealer_phone'=>$handle['contact_phone'],
                    'buyer_name'=>$value['deceased_name'],
                    'dead_id'=>$deceased_id,
                    'dead_name'=>$this->result_list['buyer_name'],
                    'funeral_type'=>$this->result_list['funeral'],
                    'handle_id'=>$this->result_list['handle'],
                    'handle_name'=>cmf_get_admin_name($this->result_list['handle']),
                    'service_status'=>1,
                    'add_time'=>time(),
                    'buried_time'=>time(),
                    'add_user'=>cmf_get_current_admin_id(),
                ];
                if ($value['deceased_name']) {
                    $buried_info = Db::name('service_buried')->where(['dead_id' => $deceased_id])->find();
                    if ($buried_info) {
                        Db::name('service_buried')->where(['id' => $buried_info['id']])->update($buried_info);
                    } else {
                        Db::name('service_buried')->insertGetId($buried_inst);
                    }
                }
            }
            return $this->success('提交成功',url("Aftersale/chooseGoods",['order_id'=>$order_id,'customer_id'=>$customer_id,'buried_id'=>$buried_id,'tomb_id'=>$tomb_id]));
        }

        if ($this->customerId==0){
            return $this->fetch('login');
        }
        $tomb_mb_list =  Db::name("tomb_mb")->alias('tm')->field('pmb.*,tm.address')
            ->join('dj_product_mb pmb','tm.mb_id = pmb.id')
            ->where(['tm.tomb_id'=>$this->result_list['tomb_id'],'tm.status'=>1])->select();

        $mb_arr=[];
        foreach ($tomb_mb_list as $km=>&$vals){
            $m_info['id'] = $vals['id'];
            $m_info['pro_name'] = $vals['pro_name'].'('.$vals['pro_code'].')';
            $m_info['regulation_name'] = $this->regulation_arr[$vals['regulation']];
            $m_info['pro_length'] = $vals['pro_length'].'mm*'.$vals['pro_width'].'mm*'.$vals['pro_height'].'mm';
            $m_info['pro_code'] = $vals['pro_code'];
            $m_info['address'] = $vals['address'];
            $m_info['mb_img_path'] = $vals['mb_img_path'];
            $m_info['pro_photo_path'] = cmf_get_image_preview_url($vals['mb_img_path']);
            $mb_arr[]=$m_info;
        }
        $this->assign('tomb_list',$mb_arr);

		return $this->fetch();
	}



	/*寄存业务*/
	public function check(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*退墓业务*/
	public function back(){
        $model = new RetreatTombModel();
	    if ($this->request->isPost()){
	        $parem= $this->request->param();
	        $restel = $model->add($parem);
	        if ($restel!=false){
	            $this->success('提交成功，待审核中',url('back'));
            }else{
	            $this->error($model->getError());
            }
        }
        if ($this->customerId==0){
            return $this->fetch('login');
        }

        $res_pay = Db::name('order_pay_log')->where(['status'=>1,'tomb_id'=>$this->tombId,'customer_id'=>$this->customerId])->find();
//        $res_pay = $model->where(['mw_id'=>$this->tombId])->find();
        $res_retreat = $model->where(['mw_id'=>$this->tombId,'order_id'=>$this->result['order_id']])->find();


        $pay_real_name = cmf_get_admin_name($res_pay['pay_real_name']);


        $refund_reason = [
            '1'=>'退墓原因1',
            '2'=>'退墓原因2',
            '3'=>'退墓原因3',
            '4'=>'退墓原因4',
        ];
        $this->assign('refund_reason',$refund_reason);
        $this->assign('pay_type',cart_type('pay'));
        $this->assign('retreat',$res_retreat);
        $this->assign('pay_real_name',$pay_real_name);

		return $this->fetch();
	}
	/*管理费业务*/
	public function manage(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	// 管理费业务
	public function protect(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        $orders = Db::name('orders')->find();
        $this->assign($orders);

        $results = Db::name('protect')->alias('p')
            ->join('protect_payment pp','pp.order_id=p.order_id')
            ->select();
        //echo Db::name('protect')->getLastSql();
        $this->assign("protect_payment", $results);

        return $this->fetch();
    }
    public function add_post()
    {
        $data = array(
            'order_id' => 1,
            'dealer' => $_POST['dealer'],
            'sex' => $_POST['sex'],
            'tel' => $_POST['tel'],
            'relation' => $_POST['relation'],
            'card_ytpe' => $_POST['card_ytpe'],
            'cart_num' => $_POST['cart_num'],
            'address' => $_POST['address'],
        );

        Db::name('protect')->insert($data);
        $this->protect_payment_add();

        $this->success("添加成功！", url("Protect/protect"));
    }
    public function protect_payment_add()
    {
        $album = array(
            'order_id' => 1,
            'price' => $_POST['price'],
            'duration' => $_POST['duration'],
            'reduce' => $_POST['reduce'],
            'total' => $_POST['total'],
            'dealers' => $_POST['dealers'],
        );
        $pay_time = $_POST['pay_time'];
        $album['pay_time'] = strtotime($pay_time);
        Db::name('protect_payment')->insert($album);
    }

	/*证件管理业务*/
	public function paperwork(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	public function paperloss(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*墓碑刻制*/
	public function carve(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*工程首页*/
	public function sale(){
        if ($this->customerId==0){
            return $this->fetch('login');
        }
		return $this->fetch();
	}
	/*墓位产品信息*/
	public function add(){
        $parentid = $this->request->param('parentid', 0, 'intval');
        $id = $this->request->param('tid', 0, 'intval');
        $this->assign("id",$id);
        $this->assign("parentid",$parentid);
		return $this->fetch();
	}


	public function art_product(){
        // 石材种类
        $this->getALlOption();

        $id = $this->request->param("id");
        $type = $this->request->param('type');
        $where = array(
            'id' => $id
        );
        $result = Db::name("product_mb")->where($where)->find();
        $this->assign($result);
        // 详情
        $infowhere = array(
            'mb_id' => $id,
            'itype' => 1
        );
        $infoData = Db::name("product_mb_info")->where($infowhere)->select();
        $this->assign('infoData', $infoData);
        // 基础
        $basewhere = array(
            'mb_id' => $id,
            'itype' => 2
        );
        $baseData = Db::name("product_mb_info")->where($basewhere)->select();
        $this->assign('baseData', $baseData);
        // 盖板
        $platewhere = array(
            'mb_id' => $id,
            'itype' => 3
        );
        $plateData = Db::name("product_mb_info")->where($platewhere)->select();
        $this->assign('plateData', $plateData);

        // 栏杆
        $railwhere = array(
            'mb_id' => $id,
            'itype' => 4
        );
        $railData = Db::name("product_mb_info")->where($railwhere)->select();
        $this->assign('railData', $railData);

        // 附件
        $annexwhere = array(
            'mb_id' => $id,
        );
        $annexData = Db::name("product_mb_annex")->where($annexwhere)->select();
        $this->assign('annexData', $annexData);
        // echo Db::name("product_mb_annex")->getLastSql();
        $this->assign('type_mb', $type);
        return $this->fetch();
    }
    /**
     * 下拉数据
     */
    public function getALlOption()
    {
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")->join("dj_cate c", "c.id = s.cate_id", "left")->select();
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));
        // 所有产品库
        $allData = Db::name("product")->field("id,pro_name as name")->select();
        $this->assign("allData", $allData);
        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annex", $annex);
        $this->assign("annexJson", json_encode($annex));
    }

    /*不良记录的查询列表*/
    public function badindex()
    {
        if ($this->customerId==0){
            return $this->fetch('login');
        }
        $results = Db::name("badlog")->alias("b")->field("b.*,b.id bid,u.user_nickname")
            ->leftJoin("user u", "u.id=b.add_user" )
            ->where("is_delete","0")
            ->where('tomb_num', $this->tomb_num)
            ->where('customer_id', $this->customerId)
//            ->where('tomb_num', "ys1001")
            ->paginate(10);
        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("page", $page);

        return $this->fetch();
    }

    /*不良记录--查看详情*/
    public function badgetdetail()
    {
        $id = $this->request->param('id');
        $result = Db::name("badlog")->alias("b")->field("u.user_nickname,b.*")
            ->leftJoin("user u", "u.id=b.add_user")
            ->where('b.id', $id)
            ->find();
        $result['add_time'] = date('Y/m/d H:i:s',$result['add_time']);
        $this->assign($result);

        // 获取购买人信息
        $this->assign("results", $this->result_list);
        return $this->fetch();
    }
    /*不良记录-删除数据*/
    public function baddelete()
    {
        $id = $this->request->param("id");

        $saveData =  Db::name("badlog")
            ->where('id', $id)
            ->find();
        $saveData['is_delete'] ='1';
        Db::name("badlog")->update($saveData);

        $this->success("删除成功", url("Aftersale/badindex"));
    }
    /*不良记录-解锁或锁定*/
    public function badlock()
    {
        $id = $this->request->param("id");
        $lock_status = $this->request->param("lock_status");

        $saveData =  Db::name("badlog")
            ->where('id', $id)
            ->find();
        $saveData['lock_status'] = $lock_status==1 ? 2: 1 ;
        Db::name("badlog")->update($saveData);

        $this->success("操作成功", url("Aftersale/badindex"));
    }
}

